package com.jumper.usbdemo;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.ftdi.j2xx.D2xxManager;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {


    private UsbManager usbManager;

    private TextView tvLog;


    private static final String Tag = "Terry";


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        usbManager = (UsbManager)getSystemService(Context.USB_SERVICE);


        tvLog = (TextView)findViewById(R.id.tvLog);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });



        registerReceiver(receiver, getFilters());


//        // 获取一个 BluetoothAdapter
//        BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(BLUETOOTH_SERVICE);
//        BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
//
//
//        BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
//            @Override
//            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
//
//                // device 扫码到的蓝牙设备
//                // rssi 蓝牙信号强弱（可用来表示距离远近）
//                // scanRecord 广播中协带的数据。
//
//            }
//        };
//        bluetoothAdapter.startLeScan(leScanCallback);
//
//        bluetoothAdapter.stopLeScan(leScanCallback);



    }



    private void getDevice(){

        HashMap<String, UsbDevice> hashMap =  usbManager.getDeviceList();



        appendText("----->" + hashMap.size());



        try {
            D2xxManager manager =  D2xxManager.getInstance(this);


            int position = manager.createDeviceInfoList(this);


            appendText("position---->"+position);


            for(Map.Entry<String,UsbDevice> deviceEntry:hashMap.entrySet()){

                UsbDevice device = deviceEntry.getValue();



                appendText("device name-----"+device.getDeviceName()+"---");
                appendText("interface  count-----"+device.getInterfaceCount()+"---");


                // 血压
                if(device.getVendorId() == 1027 && device.getProductId() == 24577){
                    appendText( "------find the --device-----");
                    int index = manager.addUsbDevice(device);
                    appendText("the index is ---->"+ index);
                }
//                Log.d("Terry",device.getDeviceName()+"-------->"+ manager.isFtDevice(deviceEntry.getValue()));
            }






//            FT_Device ft_device = manager.openByIndex(this,position);
//
//
//
//
//            if(ft_device == null){
//                Log.d("Terry","~~~~~~~sb b ");
//            }else{
//                Log.d("Terry","~~~~~~"+ft_device.toString());
//            }



        } catch (D2xxManager.D2xxException e) {
            Log.e(Tag,"error",e);
            e.printStackTrace();
        }


    }



    public void toget(View view){





//        hashMap.entrySet();

        getDevice();


    }


    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            appendText("1111111111111");
            if(UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)){

                UsbDevice usbDevice = intent.getParcelableExtra("device");


                usbManager.getDeviceList();


                appendText( usbDevice.toString());


                getDevice();


            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    private IntentFilter getFilters(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        return filter;
    }




    public void appendText(final String text){
        Log.d("Tag", text);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvLog.append(text);
            }
        });


    }





}
